<template>
  <div>
    <el-button type="primary" size="large" @click="showAddUser = true"
      >添加角色</el-button
    >
    <el-dialog v-model="showAddUser" title="添加角色" width="40%">
      <el-form
        :model="form"
        label-width="80px"
        status-icon
        :rules="rules"
        ref="ruleFormRef"
      >
        <el-form-item label="职位名称" prop="roleDesc">
          <el-input v-model="form.roleDesc" />
        </el-form-item>
        <el-form-item label="职位描述" prop="roleName">
          <el-input v-model="form.roleName" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="onsubmit(ruleFormRef)">
            提交
          </el-button>
          <el-button @click="closeDialog(ruleFormRef)">取消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { defineProps, reactive, ref } from "vue";
import { addRole } from "@/api/roleList";
import { ElMessage, ElMessageBox } from "element-plus";
const props = defineProps({
  getList: {
    type: Function,
  },
});
let showAddUser = ref(false);
let ruleFormRef = reactive({});
const form = reactive({
  roleDesc: "",
  roleName: "",
});
let rules = {
  roleDesc: [
    { required: true, message: "请输入职位名称", trigger: "blur" },
    { min: 3, max: 10, message: "职位名称3~10个字", trigger: "blur" },
  ],
  roleName: [
    { required: true, message: "请输入职位描述", trigger: "blur" },
    { min: 6, max: 18, message: "职位描述6~18个字", trigger: "blur" },
  ],
};

const closeDialog = (ruleFormRef = null) => {
  if (ruleFormRef != null) ruleFormRef.resetFields();
  showAddUser.value = false;
};
const onsubmit = (ruleFormRef) => {
  ruleFormRef.validate(async (isValid) => {
    if (isValid) {
      let res = await addRole(form);
      ElMessageBox.alert(res.meta.msg, "", {
        // if you want to disable its autofocus
        // autofocus: false,
        confirmButtonText: "确认",
        callback: () => {
          ElMessage({
            type: res.meta.status == 201 ? "success" : "error",
            message: res.meta.status == 201 ? "创建成功" : "创建失败",
          });
        },
      });
      closeDialog(ruleFormRef);
      props.getList();
    }
    // ruleFormRef.resetFields();
  });
};
</script>

<style lang="scss" scoped>
.el-dialog {
  padding: 100px;
}
</style>